package leetcode_day._2022._202202._0110;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author yzh
 * @version 1.0
 * @date 2022/2/1 23:09
 * 最长的美好子字符串
 * 算法：字符串、位运算
 */
public class _01_1763 {
    public static void main(String[] args) {
        System.out.println('A' - 'a');
        System.out.println(new _01_1763().check("Ba"));
    }

    public String longestNiceSubstring(String s) {
        int len = s.length();
        String ans = "";
        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i < len; i++) {
            for (int j = i + 1; j < len; j++) {
                String tmp = s.substring(i, j + 1);
                if (check(tmp) && tmp.length() > ans.length()) ans = tmp;
            }
        }
        return ans;
    }
    boolean check(String s) {
        Set<Character> set1 = new HashSet<>(), set2 = new HashSet<>();
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) >= 'a' && s.charAt(i) <= 'z') set1.add(s.charAt(i));
            else set2.add(s.charAt(i));
        }
        if (set1.size() != set2.size()) return false;
        for (Character c : set1) if (!set2.contains((char)(c - 32))) return false;
        return true;
    }

    // 二进制
    public String longestNiceSubstring_upgrade(String s) {
        int n = s.length();
        int idx = -1, len = 0;
        for (int i = 0; i < n; i++) {
            int a = 0, b = 0;
            for (int j = i; j < n; j++) {
                char c = s.charAt(j);
                if (c >= 'a' && c <= 'z') a |= (1 << (c - 'a'));
                else b |= (1 << (c - 'A'));
                if (a == b && j - i + 1 > len) {
                    idx = i;
                    len = j - i + 1;
                }
            }
        }
        return idx != -1 ? s.substring(idx, idx + len) : "";
    }

}
